<template>
  <el-drawer
    :title="edit?$t('message.bjkc'):$t('message.xzkc')"
    :visible.sync="isShowModal"
    size="60%"
    :before-close="handleClose"
  >
    <el-form
      ref="ruleForm"
      class="doumee-form"
      :model="param"
      :rules="rules"
      label-width="auto"
      label-suffix="："
    >
      <div class="property-title">{{ $t('message.kcxx') }}</div>
      <el-form-item :label="$t('message.kctp')" prop="configPicture">
        <transition name="fade">
          <Cropper
            v-if="dialogCropperVisible"
            :option-img="optionImg"
            :fileinfo="fileinfo"
            use-type="COURSE_IMG"
            :fixed-number="[690, 388]"
            @formSubmit="cropperSubmit"
            @formClose="cropperClose"
          />
        </transition>
        <div class="df_ac">
          <el-upload
            class="device-uploader"
            :action="uploadFileUrl"
            :data="uploadData"
            :show-file-list="false"
            :auto-upload="false"
            accept=".jpg,.png"
            :on-change="addFileChange"
          >
            <i class="el-icon-plus uploader-icon" />
            <div
              v-show="param.configPicture"
              class="file"
              :style="'background-image: url(' + param.configPicture + ')'"
            >
              <div class="delete">
                <i
                  class="el-icon-delete icon"
                  @click.stop="deleteDeviceConfigAddImage"
                />
              </div>
            </div>
          </el-upload>
          <div class="placeholder9">
            <div>{{ $t('message.jycc') }}：{{ '690px X 388px' }}</div>
            <div>{{ $t('message.zctpsm') }}</div>
          </div>
        </div>
      </el-form-item>
      <el-form-item :label="$t('message.kcmc')" prop="courseName">
        <el-input
          v-model="param.courseName"
          type="text"
          :placeholder="$t('message.qsr') + $t('message.kcmc')"
          maxlength="50"
          class="w400"
        />
      </el-form-item>
      <el-form-item :label="$t('message.kcjgy')" prop="price">
        <el-input
          v-model="param.price"
          class="w400"
          type="number"
          :disabled="edit && status == '2'"
          :placeholder="$t('message.qsr') + $t('message.kcjgy')"
        />
      </el-form-item>
      <!-- <el-form-item :label="$t('message.sfsj')" prop="upStatus">
        <el-switch
          v-model="param.upStatus"
          active-value="1"
          inactive-value="0"
          :disabled="edit && isUpload == '1'"
        />
      </el-form-item> -->
      <el-form-item :label="$t('message.sfrmkc')" prop="isHot">
        <el-switch
          v-model="param.isHot"
          :active-value="'1'"
          :inactive-value="'0'"
        />
      </el-form-item>
      <el-form-item :label="$t('message.zklx')" prop="discountType">
        <el-select v-model="param.discountType" :disabled="edit && status == '2'" :placeholder="$t('message.qxz') + $t('message.zklx')" class="w400">
          <el-option
            v-for="item in zkList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <div v-if="param.discountType == '1'" style="display: flex; flex-wrap: wrap">
        <el-form-item
          v-for="vip in vipType"
          :key="vip.id"
          align="center"
          :label="vip.cardName"
          style="width: 50%"
          :prop="`discountMap.${vip.id}`"
          :rules="{ required: true, message: $t('message.qsr') + $t('message.hyzk'), trigger: 'blur' }"
        >
          <el-input
            v-model="param.discountMap[vip.id]"
            :disabled="edit && status == '2'"
            onkeyup="value=value.replace(/[^\d.]/g, '').replace(/\.{2,}/g, '.').replace('.', '$#$').replace(/\./g, '').replace('$#$', '.').replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3').replace(/^\./g, '')"
            oninput="if(value<0||value>1) { value = ''} else {value=value.replace(/[^\d.]/g, '').replace(/\.{2,}/g, '.').replace('.', '$#$').replace(/\./g, '').replace('$#$', '.').replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3').replace(/^\./g, '')}"
            type="text"
            :placeholder="$t('message.qsr') + $t('message.hyzk') + '(' + $t('message.bllwxs') + ')'"
            maxlength="50"
          />
        </el-form-item>
      </div>

      <div class="line-style" />
      <div class="property-title">{{ $t('message.xqxx') }}</div>
      <el-form-item :label="$t('message.kcjj')" prop="introduction">
        <el-input
          v-model="param.introduction"
          type="text"
          class="w400"
          :placeholder="$t('message.qsr') + $t('message.kcjj')"
          maxlength="100"
        />
      </el-form-item>
      <el-form-item :label="$t('message.kcxq')" prop="des">
        <div class="secondColor">{{ $t('message.tpbnfz') }}</div>
        <!-- <WangEditor
          ref="myTextEditor"
          :value="param.des"
          @input="(e) => $set(param, 'des', e)"
        /> -->
        <quill-editor
            ref="myTextEditor"
            v-model="param.des"
            :placeholder="$t('message.qsrnr')"
            class="myQuillEditor"
            :options="quillOption"
          />
      </el-form-item>

      <el-form-item>
        <el-button
          v-preventReClick
          :loading="subLoading"
          type="primary"
          @click="onSubmit()"
        >{{ $t('message.tj') }}</el-button>
      </el-form-item></el-form>
  </el-drawer>
</template>

<script>
import { uploadFile, cardList, startCourse, infoCourse, editCourse } from '@/api'
import Cropper from '@/components/cropper'
// import WangEditor from '@/components/quillOption'
import { quillEditor } from 'vue-quill-editor'
import quillConfig from '@/api/sc.js'
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
export default {
  components: {
    quillEditor,
    Cropper
  },
  data() {
    return {
      quillOption: quillConfig,
      isShowModal: false,
      subLoading: false,
      dialogCropperVisible: false,
      optionImg: '',
      files: {},
      fileinfo: {},
      uploadFileUrl: uploadFile,
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < new Date(new Date().toLocaleDateString()).getTime()
        }
      },
      uploadData: {
        folder: 'COURSE_IMG',
        type: ''
      },
      zkList: [
        { value: '0', label: this.$t('message.mrzk') },
        { value: '1', label: this.$t('message.zdyzk') }
      ],
      jlList: [],
      vipType: [],
      venueId: sessionStorage.getItem('venueId'),
      param: {
        xqList: [],
        flag: '1',
        discountType: '0',
        discountMap: {}
      },
      rules: {
        configPicture: [{ required: true, message: this.$t('message.qsc') + this.$t('message.kctp'), trigger: 'change' }],
        upStatus: [{ required: true, message: this.$t('message.qxz') + this.$t('message.sfsj'), trigger: 'change' }],
        price: [
          {
            pattern: /^[0-9]{1}[0-9]*$|^0{1}\.{1}[0-9]+$|^[1-9]{1}[0-9]*\.{1}[0-9]+$/,
            required: true,
            message: this.$t('message.qsr') + this.$t('message.zqksjgy'),
            trigger: 'blur'
          }
        ],
        courseName: [{ required: true, message: this.$t('message.qsr') + this.$t('message.kcmc'), trigger: 'blur' }],
        des: [{ required: true, message: this.$t('message.qsr') + this.$t('message.kcxq'), trigger: 'blur' }],
        introduction: [{ required: true, message: this.$t('message.qsr') + this.$t('message.kcjj'), trigger: 'blur' }],
        xqList: [{ required: true, message: this.$t('message.qsc') + this.$t('message.xqtp'), trigger: 'change' }],
        discountType: [{ required: true, message: this.$t('message.qxz') + this.$t('message.zklx'), trigger: 'change' }]
      },
      edit: false,
      status: ''
    }
  },
  mounted() {
  },
  methods: {
    init(item) {
      this.isShowModal = true
      if (item && item.courseId) {
        this.courseId = item.courseId
        this.status = item.status
        this.edit = true
        this.getDetail()
      } else {
        this.getCardList()
      }
    },
    getDetail() {
      // 获取卡类型列表
      infoCourse({ param: { courseId: this.courseId }})
        .then((res) => {
          if (res.errorCode !== '000000') return
          const obj = res.record
          this.param = {
            ...obj,
            flag: '1'
          }
          this.$set(this.param, 'courseImage', obj.courseImage)
          this.$set(this.param, 'configPicture', obj.courseImageUrl)
          if (res.record.discountType === '0') {
            this.param.discountMap = {}
            this.getCardList()
          } else {
            this.param.discountMap = obj.discountMap
            const discountMap = obj.discountMap
            const arrs = []
            cardList({})
              .then((res) => {
                if (res.errorCode === '000000') {
                  const vip = res.recordList
                  vip.forEach(e => {
                    if (Object.prototype.hasOwnProperty.call(discountMap, e.id)) {
                    // if (discountMap.hasOwnProperty(e.id)) {
                      arrs.push(e)
                    }
                  })
                  this.vipType = arrs
                }
              })
              .catch((err) => {
                console.log(err)
              })
          }
        })
        .catch((err) => {
          console.log(err)
        })
    },
    check_num(e) {
      this.param.rs[e] = this.param.rs[e].replace(/[^\d]/g, '')
    },
    getCardList() {
      // 获取卡类型列表
      cardList({})
        .then((res) => {
          if (res.errorCode === '000000') {
            this.vipType = res.recordList
            const vip = res.recordList
            vip.forEach(e => {
              this.$set(this.param.discountMap, e.id, '')
            })
          }
        })
        .catch((err) => {
          console.log(err)
        })
    },
    handleClose() {
      this.isShowModal = false
      this.$emit('close')
    },
    // 上传图片成功
    uploadSuccess(res, file, fileList) {
      if (res.success) {
        this.$set(this.param, 'configPicture', res.showUrl)
        this.$set(this.param, 'courseImage', res.insertUrl)
        this.$refs.ruleForm.clearValidate()
      } else {
        this.$message.error(res.msg || this.$t('message.scsb'))
      }
    },
    // 上传图片，开始裁剪
    async addFileChange(file) {
      // 上传，拿到file文件
      this.files = file.raw
      this.$nextTick(() => {
        this.optionImg = URL.createObjectURL(file.raw)
        this.fileinfo = file.raw
        this.dialogCropperVisible = true
      })
    },
    // 裁剪确定按钮
    cropperSubmit(config) {
      // preImg 完整路径  urlPre 不包含域名
      if (config.success) {
        this.$set(this.param, 'configPicture', config.showUrl)
        this.$set(this.param, 'courseImage', config.insertUrl)
        this.$refs.ruleForm.clearValidate()
        this.dialogCropperVisible = false
      } else {
        this.$message.error(config.msg || this.$t('message.scsb'))
        this.$refs.form.clearValidate()
        this.dialogCropperVisible = false
      }
    },
    // 裁剪取消
    cropperClose() {
      this.dialogCropperVisible = false
    },
    uploadSuccesss(res, file, fileList) {
      if (res.success) {
        const arr = this.param.xqList
        res.url = res.showUrl
        arr.push(res)
        this.$set(this.param, 'xqList', arr)
        this.$refs.ruleForm.clearValidate()
      } else {
        this.$message.error(res.msg || this.$t('message.scsb'))
      }
    },
    // 删除已上传图片
    deleteDeviceConfigAddImage() {
      this.$set(this.param, 'courseImage', '')
      this.$set(this.param, 'configPicture', '')
    },
    handleRemove(file, fileList) {
      this.$set(this.param, 'xqList', fileList)
    },
    onSubmit() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          // const arr = this.param.xqList
          // let str = ''
          // arr.forEach(e => {
          //   str = str + e.insertUrl + ','
          // })
          this.param.price = Number(this.param.price)
          // this.param.images = str.substr(0, str.length - 1)
          this.param.venueId = this.venueId
          this.param.channel = '01'
          this.subLoading = true
          if (this.edit) {
            editCourse({
              param: this.param
            }).then(res => {
              this.subLoading = false
              if (res.errorCode === '000000') {
                this.$message.success(this.$t('message.tjcg'))
                this.$emit('success')
                this.$emit('close')
              }
            }).catch(err => {
              this.subLoading = false
              console.log(err)
            })
          } else {
            startCourse({
              param: this.param
            }).then(res => {
              this.subLoading = false
              if (res.errorCode === '000000') {
                this.$message.success(this.$t('message.tjcg'))
                this.$emit('success')
                this.$emit('close')
              }
            }).catch(err => {
              this.subLoading = false
              console.log(err)
            })
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 返回上一页
    goBack() {
      this.$router.replace(`/offlinecourses/onlineCoursesList`)
    }
  }
}
</script>

<style lang="scss" scoped>
@import "@/styles/variables.scss";
.device-uploader {
  width: 80px;
  height: 80px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #fff;
  cursor: pointer;
  border: 1px dashed #ccc;
  border-radius: 8px;
  transition: all 0.3s;
  margin-right: 20px;
  &:hover {
    border-color: $menuActive;
    .uploader-icon {
      color: $menuActive;
    }
  }
  ::v-deep .el-upload {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    position: relative;
    .file {
      width: 100%;
      height: 100%;
      position: absolute;
      top: 0;
      left: 0;
      background-size: contain;
      background-position: center;
      background-repeat: no-repeat;
      border-radius: 8px;
      display: flex;
      align-items: center;
      justify-content: center;
      .delete {
        background-color: rgba(0, 0, 0, 0.5);
        position: absolute;
        width: 100%;
        height: 100%;
        top: 0;
        left: 0;
        display: none;
        align-items: center;
        justify-content: center;
        .icon {
          color: #fff;
        }
      }
      &:hover {
        .delete {
          display: flex;
        }
      }
    }
  }
  .uploader-icon {
    color: #aaaaaa;
    font-size: 22px;
    transition: all 0.3s;
  }
}
.line-style {
  margin-bottom: 20px;
}
.device-uploaders {
  ::v-deep .el-upload-list__item {
    width: 80px;
    height: 80px;
  }
  ::v-deep .el-upload {
    width: 80px;
    height: 80px;
    line-height: 80px;
  }
}
</style>
